package com.hsy.bibc.modules.common;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by hsy on 2016/4/7.
 */
public abstract class CommonBaseAdapter<T> extends BaseAdapter {

    private final List<T> data;
    private LayoutInflater inflater;

    public CommonBaseAdapter(Context context, List<T> data) {
        this.data = data;
        this.inflater = LayoutInflater.from(context);
    }

    public View inflate(int layoutRes) {
        return inflater.inflate(layoutRes, null);
    }

    @Override
    public int getCount() {
        return null == data ? 0 : data.size();
    }

    @Override
    public Object getItem(int position) {
        return null == data ? null : data.get(position);
    }

    public T getData(int position){
        return null == data ? null : data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        IViewHolder holder;
        if (null == convertView) {
            holder = getViewHolder(position);
            convertView = holder.init(position);
            convertView.setTag(holder);
        } else {
            holder = (IViewHolder) convertView.getTag();
        }
        holder.setData(position, data.get(position));
        return convertView;
    }

    public abstract IViewHolder<T> getViewHolder(int position);

    public interface IViewHolder<T> {
        View init(int position);

        void setData(int position, T data);
    }
}
